import { computed, ref } from 'vue'

import { createOrder } from '@/pages/pay/api'
import { resultId, lockedStatus, updateResult } from '../data'
import { userInfo } from '@/libs/user'
import { catchFn } from '@/libs/common'
import { topMessage } from '@/components/TopMessage/data'

const showUnlockMask = ref(false)
const isAfford = computed(
  () =>
    userInfo.value &&
    lockedStatus.value &&
    (userInfo.value.balance >= lockedStatus.value.price || lockedStatus.value.itemId === 0),
)

export { showUnlockMask, isAfford }

const confirm = async () => {
  if (isAfford.value) {
    catchFn(async () => {
      const res = await createOrder({
        itemId: lockedStatus.value!.itemId,
        payChanel: lockedStatus.value!.itemId === 0 ? 3 : 1,
        testType: 'fortune',
        testResultId: resultId,
      })

      if (res.data.orderStatus === 2) {
        await updateResult()

        showUnlockMask.value = false
        topMessage.success('解锁成功')
      } else throw res
    })
  } else {
    uni.navigateTo({ url: '/pages/pay/recharge/index' })
  }
}

export { confirm }
